package duoxiancheng;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class FileUtil {
    public class Main {
        public static void main(String[] args) {
            File file = new File("test.txt");
            String data = "这是要写入文件的内容";
            String charname = "UTF-8";
            boolean append = false;
            FileUtil.writeStringToFile(file, data, charname, append);
        }
    }
    /**
     * 将指定字符串写入到文件中
     *
     * @param file     目标文件
     * @param data     要写入的字符串数据
     * @param charname 字符编码名称，例如 "UTF-8"、"GBK" 等
     * @param append   是否以追加模式写入，true为追加，false为覆盖
     */
    public static void writeStringToFile(File file, String data, String charname, boolean append) {
        try (FileOutputStream fos = new FileOutputStream(file, append);
             OutputStreamWriter osw = new OutputStreamWriter(fos, charname);
             BufferedWriter bw = new BufferedWriter(osw)) {
            bw.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}